package jay.home.bet.web.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jay.home.bet.domain.Event;
import jay.home.bet.domain.Item;
import jay.home.bet.domain.Order;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TobetAction extends BaseAction
{
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
	{
		TobetActionForm af = (TobetActionForm) form;
		
		Event event = getOddsService().getEvent(af.getEventid());
		if(event == null)return mapping.findForward("error");
		
		if(af.getGuoguan() == null || "".equals(af.getGuoguan()))
		{
			Order order = getOrderService().newOrder(request.getRemoteUser(), true);
			Item item;
			if(af.getGunqiu() == null || "".equals(af.getGunqiu()))
				item = getOrderService().generateOrderItem(order, af.getEventid(), af.getOddtype(), false, false);
			else
				item = getOrderService().generateOrderItem(order, af.getEventid(), af.getOddtype(), false, true);
			if(item == null)return mapping.findForward("error");
			item.setEvent(event);
			order.getItems().add(item);
			request.getSession().setAttribute("cart", order);
		}
		else
		{
			Order order = null;
			Object cart = request.getSession().getAttribute("cart");
			//如果cart为空， 或者cart不是过关的
			if(cart == null || ((Order)cart).getIsDanshi())order = getOrderService().newOrder(request.getRemoteUser(), false);
			else order = (Order)cart;
			Item item = getOrderService().generateOrderItem(order, af.getEventid(), af.getOddtype(), true, false);
			if(item == null)return mapping.findForward("error");
			order.setCat("过关");
			for(Item i : order.getItems())
				if(i.getEventid().equals(event.getId()))
				{
					request.setAttribute("message", "已经选择过这场比赛， 请选择其它比赛");
					return mapping.findForward("error");
				}
			item.setEvent(event);
			order.getItems().add(item);
			request.getSession().setAttribute("cart", order);
		}
		return mapping.findForward("SUCCESS");
	}
}
